'use strict';
const { Op } = require('sequelize');

module.exports = app => {
  class User extends app.Service {
    async getUserById(id) {
      try {
        const user = await this.app.model.User.findOne({ where: { id } });
        return user;
      } catch (e) {
        return null;
      }
    }

    async getUserByName(username) {
      try {
        const user = await this.app.model.User.findOne({ where: { username } });
        return user;
      } catch (e) {
        return null;
      }
    }

    async getUserByQuery(query) {
      try {
        const user = await this.app.model.User.findOne({ where: query });
        return user;
      } catch (e) {
        return null;
      }
    }

    async getAllStaff() {
      try {
        const users = await this.app.model.User.findAll({
          where: {
            [Op.not]: [
              { permission: 3 },
            ],
          },
        });
        return users;
      } catch (e) {
        return null;
      }
    }

    async getAllUsers() {
      try {
        const users = await this.app.model.User.findAll({

          attributes: [ 'username', 'id', 'permission', 'created_at', 'ticket_number', 'efficient_ticket_number', 'score' ],
        });
        return users;
      } catch (e) {
        return null;
      }
    }

    async setPermission(id, permission) {
      try {
        const users = await this.app.model.User.update({ permission }, { where: { id } });
        return users;
      } catch (e) {
        return null;
      }
    }

    async endTicket(staffId) {
      try {
        const user = await app.model.User.findOne({ where: { id: staffId } });
        const result = await user.increment('ticket_number');
        return result;
      } catch (e) {
        return null;
      }
    }

    async evaluate(staffId, score) {
      try {
        const user = await app.model.User.findOne({ where: { id: staffId } });
        await user.increment('score', { by: score });
        const result = await user.increment('efficient_ticket_number');
        return result;
      } catch (e) {
        return null;
      }
    }
  }
  return User;
};
